package hu.genius.model;

import hu.genius.model.entity.Product;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
	public static final String KEY_ID = "id";
	public static final String KEY_NAME = "name";
	public static final String KEY_PRICE = "price";
	public static final String KEY_CATEGORY_ID = "category_id";
	private static final String TAG = "DBAdapter";

	private static final String DATABASE_NAME = "DonPedro";
	private static final int DATABASE_VERSION = 2;
	private static final String PRODUCT_TABLE_NAME = "products";
	private static final String ORDER_TABLE_NAME = "orders";
	
	private final Context context;
	private DatabaseHelper DBHelper;
	private SQLiteDatabase db;

	public DBAdapter(Context ctx) {
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
		DBHelper.onCreate(db);
	}

	private class DatabaseHelper extends SQLiteOpenHelper {
		private static final String SQLLLITE_DATABASE_PATH = "/databases/DonPedro";
		private static final String DATA_PATH = "/data/data/";

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			try {
				String destPath = DATA_PATH + context.getPackageName()
						+ SQLLLITE_DATABASE_PATH;
				File f = new File(destPath);
				f.delete();
				if (!f.exists()) {
					Log.d("m", "not exist");
					CopyDB(context.getApplicationContext().getAssets().open("donpedro.sqlite"),
							new FileOutputStream(destPath));
				} else {
					Log.d("m", "exist");
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void CopyDB(InputStream inputStream, OutputStream outputStream)
				throws IOException {
			byte[] buffer = new byte[1024];
			int length;
			while ((length = inputStream.read(buffer)) > 0) {
				outputStream.write(buffer, 0, length);
			}
			inputStream.close();
			outputStream.close();
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			{
				Log.w(TAG, "Upgrading database from version " + oldVersion
						+ " to " + newVersion
						+ ", which will destroy all old data");
				db.execSQL("DROP TABLE IF EXISTS " + PRODUCT_TABLE_NAME);
				onCreate(db);
			}
		}
	}

	public Cursor getAllProducts() {
		return db.query(PRODUCT_TABLE_NAME, new String[] { KEY_ID, KEY_NAME,
				KEY_PRICE, KEY_CATEGORY_ID }, null, null, null, null, null);
	}

	public Cursor getProductsOfCategory(int categoryId) throws SQLException {
		Cursor mCursor = db.query(true, PRODUCT_TABLE_NAME, new String[] { KEY_ID,
				KEY_NAME, KEY_PRICE, KEY_CATEGORY_ID }, KEY_CATEGORY_ID + "=" + categoryId, null,
				null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	public Cursor getProduct(long rowId) throws SQLException {
		Cursor mCursor = db.query(true, PRODUCT_TABLE_NAME, new String[] { KEY_ID,
				KEY_NAME, KEY_PRICE, KEY_CATEGORY_ID }, KEY_ID + "=" + rowId, null,
				null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	public int getOrderCountByProduct(Product product) {
		return 0;
	}
	
	public void addOrder(Product product) {
		ContentValues values = new ContentValues();
		values.put("product_id", product.getId());
		values.put("quantity", 1);
		db.insert(ORDER_TABLE_NAME, null, values);
	}
	

	public Cursor getAllOrders() {
		return db.query("orders", new String[] { "id", "product_id",
				"quantity" }, null, null, null, null, null);
	}
	
	public DBAdapter open() throws SQLException {
		db = DBHelper.getWritableDatabase();
		return this;
	}
	
	public void close() {
		DBHelper.close();
	}
}